﻿using System.Configuration;
using Synology.DS.Interface.Abstract;

namespace Synology.DS.Core
{
    public class ConfigurationManager : IConfigurationManager
    {
	    private readonly Configuration _config;
	    private readonly bool _throughErrorOnEmptyParam;

	    public ConfigurationManager()
			: this(System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None), true)
	    {
		    
	    }

		public ConfigurationManager(Configuration config, bool throughErrorOnEmptyParam)
        {
	        _config = config;
			_throughErrorOnEmptyParam = throughErrorOnEmptyParam;

			ReadSettings();
        }

        public string TorrentFilesFolder { get; set; }
        public string TorrentFilesFilter { get; set; }
        public string SynologyApiUrl { get; set; }
	    public string SynologyUser { get; set; }
	    public string SynologyPassword { get; set; }
	    public string TorrentsArchiveFolder { get; set; }

	    public void Save()
	    {
			_config.AppSettings.Settings.Remove("TorrentsFolder");
			_config.AppSettings.Settings.Remove("SynologyApiUrl");
			_config.AppSettings.Settings.Remove("TorrentFilesFilter");
			_config.AppSettings.Settings.Remove("SynologyUser");
			_config.AppSettings.Settings.Remove("SynologyPassword");
			_config.AppSettings.Settings.Remove("TorrentsArchiveFolder");

			_config.AppSettings.Settings.Add("TorrentsFolder", TorrentFilesFolder);
			_config.AppSettings.Settings.Add("SynologyApiUrl", SynologyApiUrl);
			_config.AppSettings.Settings.Add("TorrentFilesFilter", TorrentFilesFilter);
			_config.AppSettings.Settings.Add("SynologyUser", SynologyUser);
			_config.AppSettings.Settings.Add("SynologyPassword", SynologyPassword);
			_config.AppSettings.Settings.Add("TorrentsArchiveFolder", TorrentsArchiveFolder);

		    _config.Save();
	    }

	    #region private 

	    private void ReadSettings()
	    {
			TorrentFilesFolder = ReadConfigParam("TorrentsFolder", true);
			SynologyApiUrl = ReadConfigParam("SynologyApiUrl", true);
			TorrentFilesFilter = ReadConfigParam("TorrentFilesFilter");
			SynologyUser = ReadConfigParam("SynologyUser", true);
			SynologyPassword = ReadConfigParam("SynologyPassword", true);
			TorrentsArchiveFolder = ReadConfigParam("TorrentsArchiveFolder", true);
	    }

	    private string ReadConfigParam(string key, bool throwIfNotDefined = false)
        {
            string result = _config.AppSettings.Settings[key].Value;

            if (string.IsNullOrWhiteSpace(result) && throwIfNotDefined && _throughErrorOnEmptyParam)
                throw new ConfigurationErrorsException(string.Format("'{0}' config parameter isn't found", key));

            return result;
        }
        #endregion
    }
}
